import React, {useEffect, useState} from "react";
import {getTrafficSummaryUsingGet} from "@/services/api-backend/trafficForecastController";
import ReactECharts from "echarts-for-react";
import {Button, Card, Col, Form, InputNumber, message, Row, Select, Space, Statistic} from "antd";
import {ArrowDownOutlined, ArrowUpOutlined, ClockCircleOutlined} from "@ant-design/icons";

export type Props = {
  infoVo: {id: number, name: string}[];
  type?:number
};
export  const TrafficSummary:React.FC<Props>=(props)=>{
  const {infoVo,type}=props
  const [interfaceNameList,setInterfaceNameList]=useState<{value: number, label: string}[]>([])
  const [data ,setData]=useState<API.TrafficSummary>()
  const [loading,setLoading]=useState<boolean>(false)
  const [formRef] = Form.useForm();
  const [days,setDays]=useState<number>(7)
  const [interfaceId,setInterfaceId]=useState<number>()

  useEffect(() => {
    if(infoVo&&infoVo.length>0){
      const items=infoVo.map(item=>({
        value:item.id!,
        label:item.name
      }))
      setInterfaceNameList(items)
      // 数据加载完成后设置表单默认值
      formRef.setFieldsValue({ interfaceId: items[0]?.value })
      loadData(infoVo[0].id,7)
    }
  }, [infoVo]);
  const loadData=async (id:number,dayCount:number=7)=>{
    setLoading(true)
    try {
        const {data:response}=await  getTrafficSummaryUsingGet({
          interfaceId:id,
          days:dayCount,
          type
        })
      if(response){
        setTimeout(()=>{
          setData(response)
          setInterfaceId(id)
          setDays(dayCount)
        },2300)
      }

    }catch (e){
      message.error("流量统计摘要查询失败: " + e);
    }finally {
      setTimeout(()=>setLoading(false),3000)
    }
  }
  const doSubmit=async (values:any)=>{
    if(!values.interfaceId){
      message.warning("请输入接口ID");
      return;
    }
    await loadData(values.interfaceId, values.days || 7);
  }
  const doReset = () => {
    formRef.resetFields();
    setData(undefined);
  };

  // 对比柱状图配置
  const comparisonChartOption = {
    title: {
      text: "流量对比分析",
      left: "center",
      textStyle: { fontSize: 16, fontWeight: "bold", color: "#333" },
    },
    tooltip: {
      trigger: "axis",
      triggerOn: "click",
      enterable: true,
      hideDelay: 300,
      backgroundColor: "rgba(255, 255, 255, 0.96)",
      borderColor: "#ddd",
      borderWidth: 1,
      textStyle: { color: "#333", fontSize: 12 },
      padding: [10, 15],
      confine: true,
      axisPointer: {
        type: "shadow",
      },
    },
    legend: {
      data: ["历史流量", "预测流量"],
      top: 40,
      left: "center",
      textStyle: { fontSize: 12 },
      icon: "roundRect",
      itemWidth: 16,
      itemHeight: 10,
    },
    grid: {
      left: "8%",
      right: "8%",
      top: "25%",
      bottom: "15%",
      containLabel: true,
    },
    xAxis: {
      type: "category",
      data: ["平均流量", "峰值流量"],
      axisLine: { lineStyle: { color: "#ddd" } },
      axisLabel: { color: "#666", fontSize: 12 },
      axisTick: { show: false },
    },
    yAxis: {
      type: "value",
      name: "请求次数",
      nameTextStyle: { color: "#666", fontSize: 12 },
      axisLine: { show: false },
      axisTick: { show: false },
      axisLabel: { color: "#666", fontSize: 11 },
      splitLine: { lineStyle: { color: "#f0f0f0", type: "dashed" } },
    },
    series: [
      {
        name: "历史流量",
        type: "bar",
        data: [data?.avgHistorical || 0, data?.maxHistorical || 0],
        itemStyle: {
          color: {
            type: "linear",
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              { offset: 0, color: "#5470c6" },
              { offset: 1, color: "#91a7ff" },
            ],
          },
          borderRadius: [6, 6, 0, 0],
        },
        label: {
          show: true,
          position: "top",
          formatter: "{c}",
          color: "#333",
          fontSize: 12,
          fontWeight: "bold",
        },
        barWidth: "40%",
      },
      {
        name: "预测流量",
        type: "bar",
        data: [data?.avgForecast || 0, data?.maxForecast || 0],
        itemStyle: {
          color: {
            type: "linear",
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              { offset: 0, color: "#91cc75" },
              { offset: 1, color: "#c8e6c9" },
            ],
          },
          borderRadius: [6, 6, 0, 0],
        },
        label: {
          show: true,
          position: "top",
          formatter: "{c}",
          color: "#333",
          fontSize: 12,
          fontWeight: "bold",
        },
        barWidth: "40%",
      },
    ],
  };

  // 增长率仪表盘配置
  const growthGaugeOption = {
    title: {
      text: "流量增长率",
      left: "center",
      textStyle: { fontSize: 16, fontWeight: "bold", color: "#333" },
    },
    tooltip: {
      formatter: "{c}%",
    },
    series: [
      {
        type: "gauge",
        min: -100,
        max: 100,
        splitNumber: 10,
        radius: "75%",
        center: ["50%", "60%"],
        startAngle: 180,
        endAngle: 0,
        axisLine: {
          lineStyle: {
            width: 20,
            color: [
              [0.3, "#ee6666"],
              [0.5, "#fac858"],
              [0.7, "#91cc75"],
              [1, "#5470c6"],
            ],
          },
        },
        pointer: {
          itemStyle: {
            color: "#333",
          },
          length: "60%",
          width: 6,
        },
        axisTick: {
          distance: -20,
          length: 8,
          lineStyle: {
            color: "#fff",
            width: 2,
          },
        },
        splitLine: {
          distance: -20,
          length: 15,
          lineStyle: {
            color: "#fff",
            width: 3,
          },
        },
        axisLabel: {
          distance: 15,
          color: "#666",
          fontSize: 11,
          formatter: function (value: number) {
            return value + "%";
          },
        },
        detail: {
          valueAnimation: true,
          formatter: "{value}%",
          color: "#333",
          fontSize: 24,
          fontWeight: "bold",
          offsetCenter: [0, "80%"],
        },
        data: [{ value: data?.growthRate || 0 }],
      },
    ],
  };
  return <>
    {/* 查询表单 */}
    <Card  style={{marginBottom:24}}>
      <Form
        form={formRef}
        layout="inline"
        onFinish={doSubmit}
        initialValues={{ days: 7 }}
      >
        <Form.Item
          label="接口"
          name="interfaceId"
          rules={[{ required: true, message: "请输入接口ID" }]}
        >
          <Select
            placeholder={"请选择接口（不选择则返回所有接口）"}
            allowClear
            style={{ width: 220 }}
            options={interfaceNameList}></Select>
        </Form.Item>
        <Form.Item label="统计天数" name="days">
          <InputNumber
            placeholder="统计天数"
            style={{ width: 150 }}
            min={1}
            max={90}
          />
        </Form.Item>
        <Form.Item>
          <Space>
            <Button type="primary" htmlType="submit" loading={loading}>
              查询
            </Button>
            <Button onClick={doReset} disabled={loading}>重置</Button>
          </Space>
        </Form.Item>

      </Form>
    </Card>
    {/* 统计卡片 */}
    {data && (
      <>
        <Row gutter={16} style={{ marginBottom: 16 }}>
          <Col span={6}>
            <Card>
              <Statistic
                title="历史平均流量"
                value={data.avgHistorical|| "暂无数据"}
                precision={2}
                valueStyle={{ color: "#5470c6", fontSize: 28 }}
                prefix={<span style={{ fontSize: 16 }}>📊</span>}
                suffix={data.avgForecast?"次":""}
              />
            </Card>
          </Col>
          <Col span={6}>
            <Card>
              <Statistic
                title="预测平均流量"
                value={data.avgForecast|| "暂无数据"}
                precision={2}
                valueStyle={{ color: "#91cc75", fontSize: 28 }}
                prefix={<span style={{ fontSize: 16 }}>🔮</span>}
                suffix={data.avgForecast?"次":""}
              />
            </Card>
          </Col>
          <Col span={6}>
            <Card>
              <Statistic
                title="流量增长率"
                value={data.growthRate|| "暂无数据"}
                precision={2}
                valueStyle={{
                  color: (data.growthRate || 0) >= 0 ? "#3f8600" : "#cf1322",
                  fontSize: 28,
                }}
                prefix={
                  (data.growthRate || 0) >= 0 ? (
                    <ArrowUpOutlined />
                  ) : (
                    <ArrowDownOutlined />
                  )
                }
                suffix={data.growthRate?"%":""}
              />
            </Card>
          </Col>
          <Col span={6}>
            <Card>
              <Statistic
                title="预测峰值时间"
                value={data.peakTime || "暂无数据"}
                valueStyle={{ color: "#faad14", fontSize: 18 }}
                prefix={<ClockCircleOutlined />}
              />
            </Card>
          </Col>
        </Row>

        <Row gutter={16} style={{ marginBottom: 16 }}>
          <Col span={6}>
            <Card>
              <Statistic
                title="历史峰值流量"
                value={data.maxHistorical||"暂无数据"}
                valueStyle={{ color: "#5470c6", fontSize: 24 }}
                prefix={<span style={{ fontSize: 14 }}>📈</span>}
                suffix={data.maxHistorical?"次":""}
              />
            </Card>
          </Col>
          <Col span={6}>
            <Card>
              <Statistic
                title="预测峰值流量"
                value={data.maxForecast||"暂无数据"}
                valueStyle={{ color: "#91cc75", fontSize: 24 }}
                prefix={<span style={{ fontSize: 14 }}>🚀</span>}
                suffix={data.maxForecast?"次":""}
              />
            </Card>
          </Col>
          <Col span={12}>
            <Card style={{ height: "100%" }}>
              <div style={{ textAlign: "center", paddingTop: 10 }}>
                <div style={{ fontSize: 14, color: "#999", marginBottom: 8 }}>
                  统计周期
                </div>
                <div style={{ fontSize: 32, fontWeight: "bold", color: "#1890ff" }}>
                  {days} 天
                </div>
              </div>
            </Card>
          </Col>
        </Row>

        {/* 图表区域 */}
        <Row gutter={16}>
          <Col span={14}>
            <Card title="流量对比柱状图">
              <ReactECharts
                option={comparisonChartOption}
                style={{ height: "400px", width: "100%" }}
                opts={{ renderer: "canvas" }}
                notMerge={true}
              />
            </Card>
          </Col>
          <Col span={10}>
            <Card title="增长率仪表盘">
              <ReactECharts
                option={growthGaugeOption}
                style={{ height: "400px", width: "100%" }}
                opts={{ renderer: "canvas" }}
                notMerge={true}
              />
            </Card>
          </Col>
        </Row>
      </>
    )}

    {/* 空状态提示 */}
    {!data && !loading && (
      <Card>
        <div style={{ textAlign: "center", padding: "60px 0", color: "#999" }}>
          <div style={{ fontSize: 48, marginBottom: 16 }}>📊</div>
          <div style={{ fontSize: 16 }}>请输入接口ID查询流量统计摘要</div>
        </div>
      </Card>
    )}
  </>
}
